import {
  BadRequestException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from './user.service';
import { JwtService } from '@nestjs/jwt';
import { RefreshToken } from '@/vos/token.vo';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async signIn(username: string, pass: string) {
    const user = await this.userService.findByUserName(username);
    if (user?.password !== pass) {
      throw new BadRequestException('用户名或密码错误！');
    }
    const { password, deleteTime, isDelete, ...payload } = user;
    const [accessToken, refreshToken] = [
      this.jwtService.sign(payload, { expiresIn: '1m' }),
      this.jwtService.sign({ id: payload.id, refresh: true }),
    ];
    return {
      accessToken,
      refreshToken,
    };
  }

  async refresh(refreshToken: string) {
    try {
      const valid = await this.jwtService.verifyAsync<RefreshToken>(
        refreshToken,
      );
      if (!valid?.refresh || !valid?.id) {
        throw new BadRequestException('refreshToken已过期或非法！');
      }
      const user = await this.userService.findOne(valid.id);
      if (!user || user.isDelete) {
        throw new BadRequestException('当前用户不存在或已注销！');
      }
      const { password, deleteTime, isDelete, ...payload } = user;
      return {
        accessToken: this.jwtService.sign(payload, { expiresIn: '1m' }),
      };
    } catch (error) {
      if (error instanceof BadRequestException) {
        throw error;
      }
      throw new BadRequestException('refreshToken已过期或非法！');
    }
  }
}
